package cn.com.acca.ma.hibernate.impl;

import cn.com.acca.ma.common.util.DateUtil;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleTypes;
import oracle.sql.ARRAY;
import oracle.sql.Datum;
import oracle.sql.STRUCT;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.jdbc.Work;

public class FindDataForSpiderWebPlotWorkImpl implements Work {

    private static Logger logger = LogManager.getLogger(FindDataForSpiderWebPlotWorkImpl.class);

    private Date boardDate;
    private BigDecimal dateNumber;
    private BigDecimal limitRate;
    private List<HashMap> list = new ArrayList<HashMap>();

    public FindDataForSpiderWebPlotWorkImpl() {
    }

    public FindDataForSpiderWebPlotWorkImpl(Date boardDate, BigDecimal dateNumber,
        BigDecimal limitRate, List<HashMap> list) {
        this.boardDate = boardDate;
        this.dateNumber = dateNumber;
        this.limitRate = limitRate;
        this.list = list;
    }

    public void execute(Connection connection) throws SQLException {
        DatabaseMetaData databaseMetaData=connection.getMetaData();
        Connection metaDataConnection=null;
        if(null!=databaseMetaData){
            metaDataConnection=databaseMetaData.getConnection();
        }
        OracleCallableStatement ocs=(OracleCallableStatement) metaDataConnection.prepareCall("{call PKG_BOARD_INDEX.FIND_DATA_FOR_SPIDER_WEB_PLOT(?,?,?,?)}");
        ocs.setString(1, DateUtil.dateToString(boardDate));
        ocs.setBigDecimal(2, dateNumber);
        ocs.setBigDecimal(3, limitRate);
        ocs.registerOutParameter(4, OracleTypes.ARRAY,"T_BOARD_RESULT_ARRAY");
        ocs.execute();
        ARRAY array=ocs.getARRAY(4);
        Datum[] datas=(Datum[]) array.getOracleArray();
        if(null!=datas){
            for (int i = 0; i < datas.length; i++){
                if(datas[i]!=null&&((STRUCT) datas[i])!=null){

                    Datum[] boardResultAttributes = ((STRUCT) datas[i]).getOracleAttributes();
                    HashMap hashMap=new HashMap();
                    hashMap.put("boardDate", boardResultAttributes[0].dateValue());
                    hashMap.put("boardId", boardResultAttributes[1].bigDecimalValue());
                    hashMap.put("stockAmount", boardResultAttributes[2].bigDecimalValue());
                    list.add(hashMap);
                }else{
                    logger.info("datas["+i+"] is null.");
                }
            }
        }
    }
}
